"""
@Author:WKVugen
@Time:2023-06-28
@Description: 页面对象层
"""
import time
from aip import AipOcr
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from base.base_page import BasePage
from utils.config import Config
from utils.log import logger


class LoginPage(BasePage):
    con = Config()
    test_info = con.get('test_info')
    baidu_orc = con.get('baidu_orc')
    # 页面元素
    username_loc = (By.XPATH, "//input[@placeholder='账号']")
    password_loc = (By.XPATH, "//input[@placeholder='密码']")
    pic_loc = ("css selector", 'img')
    code_loc = (By.XPATH, "//input[@placeholder='验证码']")
    submit_loc = (By.XPATH, "//*[@id='app']/div/div[1]/form/div[4]/div/button/span/span")
    except_loc = (By.XPATH, "//span[text()='供应商招募管理']")

    # 页面动作
    def login_demand(self, user_name= test_info['user_name'], password= test_info['password']):
        time.sleep(2)
        self.set_keys(LoginPage.username_loc, user_name)
        self.set_keys(LoginPage.password_loc, password)
        while True:
            pic = self.locator_element(LoginPage.pic_loc)
            # 实例对象
            client = AipOcr(LoginPage.baidu_orc["appid"], LoginPage.baidu_orc["apikey"], LoginPage.baidu_orc["secretkey"])
            data = pic.screenshot_as_png  # 截图成png文件
            res = client.basicAccurate(data, {})
            # logger.info("百度AIP接口返回数据为：%s", res)
            logger.info("百度AIP接口返回数据为：{}".format(res))
            # print(res)
            logger.info("截取后的数据为：{}".format(res["words_result"][0]["words"]))
            # print(res["words_result"][0]["words"])
            val = res["words_result"][0]["words"][0:3]
            try:
                # print(f"识别验证码并计算后的值为：{int(eval(val))}")
                logger.info("识别验证码并计算后的值为：%d", int(eval(val)))
                self.clear(LoginPage.code_loc)
                self.set_keys(LoginPage.code_loc, int(eval(val))) # 计算截取后的值且转换成整数
            except Exception as e:
                # print(e)
                logger.exception(e)
                # 此操作仅为了报错填充验证码
                self.set_keys(LoginPage.code_loc, "1234")
            # 点击登陆
            self.click(LoginPage.submit_loc)
            time.sleep(2)
            # 断言判断
            eles = self.locator_elements(LoginPage.except_loc)
            time.sleep(2)
            if eles:
                break
            # except_val = self.get_except_value(LoginPage.except_loc ,"供应商招募管理")
            # time.sleep(2)
            # if except_val:
            #     break

    def get_except_value(self):
        return self.get_value(LoginPage.except_loc)